setwd("/Users/mihwa/Google drive/Matching_optional protocol")        
data<-read.dta("/Users/mihwa/Google drive/Matching_optional protocol/matchicerd.dta")
attach(data)

# The following will run a caliper matching algorithm on the collapsed ICERD data.
# data will run matching diagnostics.

matchicerd_II <- matchit(icerdboth ~ icerdonly+ p_polity2+ trans+ lnwdi_gdpc+ wdi_gdpgr+ ciri_empinx_new+ ucdp_type3+LINVP+eeuro+ lame+ meast+ ssafr+ easia+ seasia+ sasia+ pacific+ caribbean, data=data, method="genetic", estimand="ATT", pop.size=200, int.seed=9)
matcheddata_II<-match.data(matchicerd_II)
write.dta(matcheddata_II, file="matchedicerd_II.dta")

## balance checking

covar<-data[,c("icerdonly", "p_polity2", "trans","lnwdi_gdpc","wdi_gdpgr", "ciri_empinx_new", "ucdp_type3",
               "LINVP","eeuro", "lame", "meast", "ssafr", "easia", "seasia", "sasia", "pacific", "caribbean")]

fmla <- as.formula(paste("icerdboth~",paste(names(covar),collapse="+")))

g.weights <- GenMatch(Tr=icerdboth, X=covar, BalanceMatrix=covar, estimand="ATT",  pop.size= 200,int.seed=9)
mout.gm <-  Match(INVP, icerdboth,covar,BiasAdjust=F,Weight.matrix=g.weights, estimand="ATT")

bout.gm <- MatchBalance(fmla,match.out = mout.gm,print.level=0,ks=FALSE)
bal.gm <- baltest.collect(matchbal.out=bout.gm,var.names=colnames(covar),after=TRUE)
bal.gm2 <- baltest.collect(matchbal.out=bout.gm,var.names=colnames(covar),after=FALSE)

bal.gm=bal.gm[,c("mean.Tr","mean.Co","sdiff.pooled","T pval")]
bal.gm2<-bal.gm2[,c("mean.Tr","mean.Co","sdiff.pooled","T pval")]
bal=cbind(bal.gm2,bal.gm)
bal=round(bal,3)
bal=data.frame(bal)
#colnames(bal) <- c("var", "mean_Tr","mean_Co","sdiff_pooled","pval","mean_Tr2","mean_Co2","sdiff_pooled2","pval2")

write.csv(bal,"bal_icerd_II.csv")
